package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spbsu.electromenu.model.Dish;
import ru.spbsu.electromenu.model.Tag;
import ru.spbsu.electromenu.service.DishService;
import ru.spbsu.electromenu.service.TagService;
import ru.spbsu.electromenu.util.collections.CollectionUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Date: 5/2/11
 * Time: 12:58 AM
 *
 * @author Artem Titov
 */
public class ShowDishServlet extends SpringHttpServlet {
    private static Logger logger = LoggerFactory.getLogger(ShowDishServlet.class);
    private DishService dishService;
    private TagService tagService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        dishService = getBean("dishService");
        tagService = getBean("tagService");
        if (dishService == null || tagService == null) {
            logger.error("Failed to instantiate necessary services");
            isValid = false;
            throw new IllegalStateException("Failed to instantiate necessary services");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!isValid) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can't initialize environment");
            return;
        }
        final List<Dish> dishes = dishService.getAll();
        final Map<Integer, Tag> tags = CollectionUtils.mapFromCollection(tagService.getAll());
        for (final Dish dish : dishes) {
            dish.injectTag(tags);
        }
        request.setAttribute("dishes", dishes);
        final RequestDispatcher dispatcher = request.getRequestDispatcher("showDish.jsp");
        if (dispatcher != null) {
            dispatcher.forward(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
